package crawler.lifan;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import util.HttpConnectionGet;
import util.MybatisTool;

public class LiFanQiCheCrawler {
	public List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		try {
			String getData = "http://auto.lifan.com/ser/jxs/";
			String sourceCode = HttpConnectionGet.getJson(getData);
			int start = sourceCode.indexOf("var data");
			int end = sourceCode.indexOf("console.log(data);");
			String data = sourceCode.substring(start, end);
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("js");
			String dealerStr = (String) engine.eval(data + ";JSON.stringify(data)");
			JSONArray dealers = JSON.parseArray(dealerStr);
			for (int i = 0; i < dealers.size(); i++) {
				JSONObject dealer = dealers.getJSONObject(i);
				String name = dealer.getString("title");
				String province = dealer.getString("province");
				String city = dealer.getString("city");
				String address = dealer.getString("address");
				String sellTell = dealer.getString("tel");
				JSONArray point = dealer.getJSONArray("point");
				String lng = null;
				String lat = null;
				if (point.size() == 2) {
					lng = point.getString(0);
					lat = point.getString(1);
				}

				AgencyEntity agency = new AgencyEntity();
				agency.setdCloseDate(null);
				agency.setdOpeningDate(null);
				agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
				agency.setnBrandID(-1);
				agency.setsBrand("力帆");

				agency.setnDealerIDWeb(-1);
				agency.setnManufacturerID(-1);
				agency.setsManufacturer("力帆汽车");

				agency.setnState(1);
				agency.setsAddress(address);
				agency.setsCity(city);
				agency.setsCustomerServiceCall(null);
				agency.setsDealerName(name);
				agency.setsDealerType(null);
				agency.setsProvince(province);
				agency.setsSaleCall(sellTell);
				agency.setsLongitude(lng);
				agency.setsLatitude(lat);
				list.add(agency);
			}

		} catch (Exception e) {
			throw new RuntimeException("获取经销商异常", e);

		}
		return list;
	}

	public static void main(String[] args) {
		LiFanQiCheCrawler crawler = new LiFanQiCheCrawler();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for (AgencyEntity agency : agencys) {
			 MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");

	}

}
